<?php
 //============================================================================
 // ____________________________PLIGG TEAM ADDON_______________________________
 //
// This CLASS was created by AnAlienHolakres3 ||| XXXXX  XX     XX XXXX   XXXX
// (c) 2007-2008                Jakub Holasek ||| XXXXX  XX     XX X      X
// @last_update                    21/02/2008 ||| XX     XX     XX X  XX  X  XX
// @version                              0.69 ||| XX     XXXXXX XX XXXXX  XXXXX
//
// This file can be used by Pligg community.
//=============================================================================

// Class TaskFiles contains general information about task files. 
// Each files is saved INTO  DATABASE, no filesystem 
  

class TaskFile {
 
    
    private $taskfile_id=0;
    private $taskfile_team_id=0;
    private $taskfile_task_id=0;
    private $taskfile_revision=0;
    private $taskfile_date='';
    private $taskfile_name='';
    private $taskfile_content;
    private $taskfile_size = 0;
    private $taskfile_downloads=0;    
    //settings  
    private $revisions_in_database=3;
    private $maximum_filesize=5580000;   //when change change in lang_conf.conf
    private $maximum_taskfile_name_length=255; //this is max in database also
  
    private $taskfiles_data;
    private $read = true;                                         
    
    //============================================================================
    //  Function read_taskfiles() gets taskfiles data (array) from database
    //  This function DOES NOT read file content    
    //============================================================================      
    
    function read_taskfiles() {
        global $db;
        
       $team_id = $this->taskfile_team_id;
       $task_id = $this->taskfile_task_id;
       
              
      
      //get all taskfiles (meta) data in team
      $taskfiles_data = $db->get_results("SELECT taskfile_id,taskfile_revision,taskfile_date,taskfile_name,taskfile_size,
                                        taskfile_task_id,taskfile_downloads FROM ".
                                        table_taskfiles . " WHERE taskfile_team_id=$team_id ORDER BY taskfile_revision DESC");
                                   
          if ($taskfiles_data) {   
              $this->taskfiles_data=$taskfiles_data;              
              
               return true;
               $this->read = true;    
           }
              
              $this->read = false;
              return false;
    } 
    
    //============================================================================
    //  Function read_taskfilecontent() gets specific taskfile content from database  
    //============================================================================ 
    
    function read_taskfile_content() {
      global $db;
      
      $team_id = $this->taskfile_team_id;
      $task_id = $this->taskfile_task_id;
      $fileid = $this->taskfile_id;
      
      $file_content=$db->get_var("SELECT taskfile_content FROM " . table_taskfiles . " WHERE taskfile_id=$fileid AND  
                    taskfile_team_id=$team_id AND taskfile_task_id=$task_id");
                    
      $this->taskfile_content = $file_content; 
        
        
    }
    

    
    //============================================================================
    //  Function fill_print() assign team taskfiles smartys
    //============================================================================
      
      function fill_print()
      {
          global $main_smarty,$current_user;                                   
              
              $tdata = $this->taskfiles_data;
              $team = new Team;
              $language = $team->get_language();                
              $maxsize = $this->maximum_filesize;          
          if ($tdata) {   
                
                  foreach ($tdata as $file_meta_data) {                      
                                                         
                  $taskfile_id[] = $file_meta_data->taskfile_id;
                  $taskfile_task_id[] = $file_meta_data->taskfile_task_id;
                  $taskfile_downloads[] = $file_meta_data->taskfile_downloads;
                  $taskfile_revision[] = $file_meta_data->taskfile_revision;
                  $taskfile_name[] = utf8_decode($file_meta_data->taskfile_name);
                  $taskfile_size[] = round($file_meta_data->taskfile_size/1024,1);
                  
                
                                 
                  if ($language == "en"){
                  $taskfile_date[] = date('Y/d/m h:i a',strtotime($file_meta_data->taskfile_date)); 
                
                  
                  } else {                                       
                  $taskfile_date[] = date('d.m.Y H:i',strtotime($file_meta_data->taskfile_date));                                     
                  }  
                    
                 } 
                                 
                 //$main_smarty->assign('current_user_crypt',$current_user_crypt);
                 //$main_smarty->assign('current_user_id',$current_user->user_id);
                 
                $main_smarty->assign('taskfile_id', $taskfile_id);
                $main_smarty->assign('taskfile_task_id', $taskfile_task_id);
                $main_smarty->assign('taskfile_downloads', $taskfile_downloads);
                $main_smarty->assign('taskfile_revision', $taskfile_revision);
                $main_smarty->assign('taskfile_name', $taskfile_name);
                $main_smarty->assign('taskfile_size', $taskfile_size);
                
             }
             $main_smarty->assign('maximum_taskfilesize',$maxsize);                                                                              
      } 
    
    //============================================================================
    //  Function store() save task file into databaase
    //============================================================================
    
    function store() {
        global $db;
        
        $team_id = $this->taskfile_team_id;
        $task_id = $this->taskfile_task_id;                
        $revision = $this->taskfile_revision;
        $date = $this->taskfile_date;
        $size = $this->taskfile_size;
        $content = $this->taskfile_content;
        $name = $this->taskfile_name;
    
        if (!$this->taskfile_downloads){ $downloads=0;}
        if (!$this->taskfile_date){ $filedate=time();}
        

             $sql = "INSERT INTO " . table_taskfiles . " (taskfile_team_id, taskfile_task_id, taskfile_downloads, taskfile_revision, 
               taskfile_date, taskfile_name, taskfile_content, taskfile_size) VALUES ($team_id, $task_id, $downloads, $revision, FROM_UNIXTIME($filedate),
                     '$name', '$content', $size)"; 
             
        if($db->query($sql)){   
            return true;     
              
        } 
            return false;       
                                              
       }                                
    
    //============================================================================
    //  Function update_taskfile_downloads() refersh taskfile downloads
    //============================================================================      
    
    function update_taskfile_downloads() {
        global $db ;
        
        $team_id = $this->taskfile_team_id;
        $task_id = $this->taskfile_task_id;
        $id = $this->taskfile_id;
        
         $current_downloads = $db->get_var("SELECT taskfile_downloads FROM ". table_taskfiles . " WHERE 
                                             taskfile_id=$id AND taskfile_task_id=$task_id AND taskfile_team_id=$team_id");
        $current_downloads++;               
        
          $sql="UPDATE ".table_taskfiles . " SET taskfile_downloads=". $current_downloads . " WHERE 
                taskfile_id=$id AND taskfile_task_id=$task_id AND taskfile_team_id=$team_id";
                                 
        if($db->query($sql)){   
            return true;     
              
        } 
            return false;   
    }
    
      //============================================================================
    //  Function update_taskfile_revision() gets taskfile revision
    //============================================================================      
    
    function read_taskfile_revision() {
        global $db ;
        
        $team_id = $this->taskfile_team_id;
        $task_id = $this->taskfile_task_id;
        
         $revision = $db->get_var("SELECT taskfile_revision FROM ". table_taskfiles . " WHERE 
                                  taskfile_task_id=$task_id AND taskfile_team_id=$team_id ORDER BY taskfile_date DESC LIMIT 1");
                                                                                                                                                                               
        $this->set_taskfile_revision($revision); 
        
        
    }   
    
    
    //============================================================================
    //  Function delete_old_revisions() checks if only the 3 latest revisions of
    //  taskfiles are in database and delete all older
    //============================================================================ 
    
    function delete_old_revisions()
    {
      global $db;
      $rev = $this->taskfile_revision;
      $revisions_to_delete = $rev - $this->revisions_in_database;
      
      $team_id = $this->taskfile_team_id;
      $task_id = $this->taskfile_task_id;
      
      if ($rev >= 3){
        $count = $db->get_var("SELECT count(taskfile_id) FROM ". table_taskfiles . " WHERE taskfile_task_id=$task_id AND taskfile_team_id=$team_id");  
        $db->query("DELETE FROM ". table_taskfiles . " WHERE  taskfile_task_id=$task_id AND taskfile_team_id=$team_id AND taskfile_revision <= $revisions_to_delete") ;
      }
    
     }     
    
    
      //==============================================================================
      // Function save_taskfile()  set values  and saves file to database           
      //==============================================================================  
      
      function save_taskfile()
      {      global $current_user,$db;
         
          
         
         $this->set_taskfile_task_id($_POST['task_id']);                                                                                                      
         $this->set_taskfile_team_id($_REQUEST['id']);     
                      
         $this->read_taskfile_revision();   
         $revision = $this->taskfile_revision+1;
         $this->set_taskfile_revision($revision);
    
         $tmpName=$_FILES['taskfile']['tmp_name'];
         $fp      = fopen($tmpName, 'r');

               
         $content = fread($fp, filesize($tmpName));                  
         //$content = "0x".bin2hex(file_get_contents($tmpName));
         
         $content = addslashes($content);        
                           
         fclose($fp);
                               
         $this->set_taskfile_name(utf8_encode(addslashes($_FILES['taskfile']['name'])));
         $this->set_taskfile_content($content); 
         $this->set_taskfile_size($_FILES['taskfile']['size']);                     
          
          //store to database
          if (!$this->store()) { 
              //cannot save to dabase
              return false;
          }

          return true;
      }
      
      
    //=================================================================================  
    //  Function can_i_download() check if user can download  task file
    //  Task files can be downloaded:
    //  1) by every (logged) site user IF team publicity is PUBLIC and team rating = 0
    //  2) by every team member IF team publicity is PRIVATE and team rating = 0
    //  3) by team member whose task rating is greater or equal minimal team rating
    //  4) every team member can download its own file
    
    //  It means if team publicity is public and team_rating > 0 only the same 
    //  members as in group 3) can download    
    //
    //  If member has more tasks, minimum rating value MUST be equal or greater in
    //  each of tasks to download other team member files
    //
    //  If user has no tasks then he cannot download files either, the only person who
    //  can download files without tasks is TEAM CREATOR
    //
    //  If team creator has task AND this task IS RATED then his/her task rating 
    //  must be also equal or greater  minimal team rating to download others files
    //
    //  If team member is file creator then this member can download this file always
    //=================================================================================  
function can_i_download()
{
    
    $team_id = $this->taskfile_team_id;
    $task_id = $this->taskfile_task_id;
    
    $team = new Team;
    $taskrating = new TaskRating;
    $task = new Task;
    
    $task->set_task_team_id($team_id);
    $task->set_task_id($task_id);    
    $task->read_basic();
    
    $team->set_id($team_id);
    $team->read(true);
    $trv = $team->get_team_rating();
    
    
    if ($team->check_team_access()) {
        // 1), 2)
        if ($team->get_team_rating()==0) {
            return true;
            
            // task (file) creator
        } else if ($task->is_task_worker()) {   
            return true;
            // 3)
        } else if ($trv > 0) {
            //for team administrator (creator)
            if ($team->is_team_creator()) {
                $ratings = $taskrating->get_user_taskrating_values($team_id);
                
                // if team creator has NOT rated tasks
                if (!$ratings) {
                    return true;
                    
                } else {
                    if (is_array($ratings)) {
                        foreach($ratings as $rating_value) {
                            if ($rating_value->average_rating < $trv) {
                                return false;
                            }
                            return true;
                        }
                    } else if ($ratings >= $trv) {
                        return true;
                    }
                    return false;
                    
                    
                }
                // normal team member
            } else {
                $ratings = $taskrating->get_user_taskrating_values($team_id);
                
                // if team member has not rating then he/her is NOT permitted to download
                if (!$ratings) {
                    return false;
                }
                if (!$ratings) {
                    return true;
                    
                } else {
                    if (is_array($ratings)) {
                        foreach($ratings as $rating_value) {
                            if ($rating_value->average_rating < $trv) {
                                return false;
                            }
                            return true;
                        }
                    } else if ($ratings >= $trv) {
                        return true;
                    }
                    return false;
                }
                
            }
        }
    }
    return false;
}
    //========================================================================
    // Function download_taskfile() download desired file    
    //========================================================================    
    
    function download_taskfile() {
     global $db;
     $id = $this->taskfile_id;
     $task_id = $this->taskfile_task_id;
     $team_id = $this->taskfile_team_id;
     
     $file = $db->get_row("SELECT taskfile_name, taskfile_size, taskfile_content FROM " . table_taskfiles . 
                            " WHERE taskfile_id=$id AND taskfile_task_id=$task_id AND taskfile_team_id=$team_id");
      $name = utf8_decode($file->taskfile_name);      
      $name = str_replace(' ','_',$name);                 
      $type = "application/octet-stream";  
     // $type = "application/zip";  
      $size = $file->taskfile_size;
      $content = $file->taskfile_content;

      ob_clean();
       header("Content-type: $type");   // - does not work in ie
       header("Content-length: $size");
       header("Content-Description: VŠElink team file");
       header("Content-Disposition: attachment; filename=$name");       
       echo $content;         
       exit;                                          



//  echo $data;
                            
    }                            
           
 //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 //  CHECKING FUNCTIONS
 //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
     
      
    //========================================================================
    // Function check_taskfile_name checks if taskfile name is ok
    // @return true if it is correct otherwise false
    //========================================================================    

    function check_taskfile_name($name) {
        $team = new Team; 
         if ($team->strlen_utf8(strip_tags(trim($name)))==0 ||  $team->strlen_utf8(strip_tags(trim($name))) > $this->maximum_taskfile_name_length){   
             return false;
         }    
             return true;            
    }     
    
       
    //========================================================================
    // Function check_taskfile_size_x checks if taskfile size is not too big
    // @return true if it is correct otherwise false
    //========================================================================    

    function check_taskfile_size_max($size) {   
         if ($size > $this->maximum_filesize){   
             return false;
         }    
             return true;            
    }
    
    //========================================================================
    // Function check_taskfile_size_x checks if taskfile size is not 0
    // @return true if it is correct otherwise false
    //========================================================================    

    function check_taskfile_size_min($size) {           
         if ($size ==0){   
             return false;
         }    
             return true;            
    }    
    
    //========================================================================
    // Function check_taskfile_type checks if taskfile type is ZIP
    // @return true if it is correct otherwise false
    //========================================================================    

    function check_taskfile_type($name) {  
        $team = new Team;
            
        $len = strlen($name);           
        
         if (substr($name,$len-4,4)==".zip"){   
             return true;
         }  
             return false;            
    }  
    
    //========================================================================
    // Function check_taskfile_saved checks if file is certainly saved
    // @return true if it is  otherwise false
    //========================================================================    

    function check_taskfile_saved() {
   
   
    }  

 //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
 //  SETTING FUNCTIONS
 //XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
   
    //============================================================================
    //  Function set_taskfile_id() sets taskfile id
    //  @param id
    //============================================================================      
    function set_taskfile_id($id) {
     $this->taskfile_id = $id;
    } 
   
   //============================================================================
    //  Function set_taskfile_team_id() sets taskfile team id
    //  @param team_id
    //============================================================================      
    function set_taskfile_team_id($team_id) {
     $this->taskfile_team_id = $team_id;
    }  
    
    //============================================================================
    //  Function set_taskfile_task_id() sets taskfile task id
    //  @param task_idi
    //============================================================================      
    function set_taskfile_task_id($task_id) {
     $this->taskfile_task_id = $task_id;
    } 
    
    //============================================================================
    //  Function set_taskfile_name() sets taskfile name
    //  @param name
    //============================================================================      
    function set_taskfile_name($name) {
        global $db;
     $name = htmlspecialchars($db->escape(strip_tags($name)));            
     $this->taskfile_name = $name;
    } 
    
    //============================================================================
    //  Function set_taskfile_content() sets taskfile content
    //  @param content
    //============================================================================      
    function set_taskfile_content($content) {
        global $db;
        
         
     $this->taskfile_content = $content;
    } 
    
    //============================================================================
    //  Function set_taskfile_size() sets taskfile size
    //  @param size
    //============================================================================      
    function set_taskfile_size($size) {    
     $this->taskfile_size = $size;
    } 

    //============================================================================
    //  Function set_taskfile_revision() sets taskfile revision 
    //  @param revision     
    //============================================================================      
    function set_taskfile_revision($revision) {
     $this->taskfile_revision = $revision;      
    } 

    //============================================================================
    //  Function switch_file_error() returns appropiable error number
    //  @param revision     
    //============================================================================      
    function switch_file_error($error) {
       switch ($_FILES['taskfile'] ['error'])
            {  case 1:
                    $team_error[] = 24;                    
               break;
               
               case 2:
                    $team_error[] = 24;                    
               break;
               
               case 3:
                    $team_error[] = 23;                    
               break;
                   
               case 4:
                    $team_error[] = 26;                    
               break;
         } 
         
         return $team_error;  
    }
  

    //============================================================================
    //  Function get_taskfile_downloads() returns taskfile downloads value    
    //============================================================================      
    function get_taskfile_downloads() {
     return $this->taskfile_downloads;
    } 
      
}
?>

